package 单链表;

public class Basic {
    public static ListNode pushFront(ListNode head, int val) {
        //头插,返回新链表的头结点
        ListNode node=new ListNode(val);
        node.next=head;

        return node;
    }
    public static void printLinkedList(ListNode head) {

        for(ListNode cur=head;cur!=null;cur=cur.next) {
            System.out.printf("%d ",cur.val);
        }
        System.out.println();
    }


    public static ListNode popFront(ListNode head) {
        //头删,返回新链表的头结点
        if(head==null) {
            throw new RuntimeException("链表为空 不处理");
        }
        return head.next;

    }

    public static ListNode pushBack(ListNode head,int val) {
        //尾插
        ListNode node=new ListNode(val);
        if(head!=null) {
            ListNode last=head;
            while (last.next!=null){
                last=last.next;
            }
            //此时last.next为空，last指向最后一个对象
            last.next=head;
            return head;
        }else {
            return node;
        }
    }

    public static ListNode popBack(ListNode head) {
        //尾删
        if(head==null) {
            throw new RuntimeException("链表为空 不处理");
        }

        if(head.next!=null) {
            //该链表至少有两个结点
            ListNode last=head;
            while (last.next.next!=null) {
                last=last.next;
            }
            //last指向倒数第二个结点
            last.next=null;
            return head;
        }else {
            //该链表只有1个结点
            return null;
        }

    }


    public static void main(String[] args) {
        ListNode head=null;
        head=pushFront(head,1);
        head=pushFront(head,2);
        printLinkedList(head);

        head=popBack(head);
        printLinkedList(head);
    }
}
